package com.ruoyi.background.service.impl;

import com.ruoyi.background.domain.AppGradeRecord;
import com.ruoyi.background.domain.AppWechatUser;
import com.ruoyi.background.mapper.AppWechatUserMapper;
import com.ruoyi.background.service.IAppGradeRecordService;
import com.ruoyi.background.service.IAppWechatUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 微信小程序用户Service业务层处理
 *
 * @author susu
 * @date 2024-08-17
 */
@Service
public class AppWechatUserServiceImpl implements IAppWechatUserService {
    @Autowired
    private AppWechatUserMapper appWechatUserMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private WechatApiServiceImpl wechatApiService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private IAppGradeRecordService gradeRecordService;

//    @Autowired
//    private Toke

    /**
     * 查询微信小程序用户
     *
     * @param id 微信小程序用户主键
     * @return 微信小程序用户
     */
    @Override
    public AppWechatUser selectAppWechatUserById(Long id) {
        return appWechatUserMapper.selectAppWechatUserById(id);
    }

    /**
     * 通过openid查询
     *
     * @param openid openid
     * @return 结果
     */
    @Override
    public AppWechatUser selectAppWechatByOpenid(String openid) {
        return appWechatUserMapper.selectAppWechatByOpenid(openid);
    }

    /**
     * 通过userId获取
     *
     * @return 结果
     */
    @Override
    public AppWechatUser selectAppWechatByUserId() {
        return appWechatUserMapper.selectAppWechatByUserId(SecurityUtils.getUserId());
    }

    /**
     * 通过userId获取
     *
     * @return 结果
     */
    @Override
    public AppWechatUser selectAppWechatByUserId(Long userId) {
        return appWechatUserMapper.selectAppWechatByUserId(userId);
    }


    /**
     * 查询微信小程序用户列表
     *
     * @param appWechatUser 微信小程序用户
     * @return 微信小程序用户
     */
    @Override
    public List<AppWechatUser> selectAppWechatUserList(AppWechatUser appWechatUser) {
        return appWechatUserMapper.selectAppWechatUserList(appWechatUser);
    }

    /**
     * 新增微信小程序用户
     *
     * @param appWechatUser 微信小程序用户
     * @return 结果
     */
    @Override
    public int insertAppWechatUser(AppWechatUser appWechatUser) {
        appWechatUser.setCreateTime(DateUtils.getNowDate());
        appWechatUser.setLastLoginTime(DateUtils.getNowDate());
        return appWechatUserMapper.insertAppWechatUser(appWechatUser);
    }

    /**
     * 修改微信小程序用户
     *
     * @param appWechatUser 微信小程序用户
     * @return 结果
     */
    @Override
    public int updateAppWechatUser(AppWechatUser appWechatUser) {
        return appWechatUserMapper.updateAppWechatUser(appWechatUser);
    }

    /**
     * 批量删除微信小程序用户
     *
     * @param ids 需要删除的微信小程序用户主键
     * @return 结果
     */
    @Override
    public int deleteAppWechatUserByIds(Long[] ids) {
        return appWechatUserMapper.deleteAppWechatUserByIds(ids);
    }

    /**
     * 删除微信小程序用户信息
     *
     * @param id 微信小程序用户主键
     * @return 结果
     */
    @Override
    public int deleteAppWechatUserById(Long id) {
        return appWechatUserMapper.deleteAppWechatUserById(id);
    }


    /**
     * 微信用户登录
     *
     * @param wechatUser 登录信息
     * @return
     */
    @Override
    @Transactional
    public AjaxResult weChatUserLogin(AppWechatUser wechatUser) {
        //此时此刻未进行登录  通过手机号查询是否有信息
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("flag", true);
        SysUser user = sysUserService.selectUserByPhone(wechatUser.getPhoneNumber());
        if (ObjectUtils.isEmpty(user)) { //系统不存在手机号
            ajaxResult.put("isExit", false);
            ajaxResult.put("phone", wechatUser.getPhoneNumber());
            return ajaxResult;
        }
        ajaxResult.put("isExit", true);
        // 查询此手机好是否被被其他手机号码绑定
        AppWechatUser query = appWechatUserMapper.selectUserByUserIdWithoutPhoneNumber(wechatUser.getOpenid(), wechatUser.getPhoneNumber());
        if (!ObjectUtils.isEmpty(query)) {
            throw new RuntimeException("手机号：" + wechatUser.getPhoneNumber() + " 已被其他微信绑定！");
        }
        if (ObjectUtils.isEmpty(wechatUser.getUserId())) {
            wechatUser.setUserId(user.getUserId());
            wechatUser.setGrade(500);
            wechatUser.setLastLoginTime(DateUtils.getNowDate());
            this.updateAppWechatUser(wechatUser);
            AppGradeRecord record = new AppGradeRecord();
            record.setUserId(user.getUserId());
            record.setGrade(500);
            record.setType(0);
            record.setBeforeGrade(0);
            record.setCreateTime(DateUtils.getNowDate());
            record.setRemark("首次登录系统奖励");
            gradeRecordService.insertAppGradeRecord(record);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String nowFormat = simpleDateFormat.format(DateUtils.getNowDate());
            String lastFormat = simpleDateFormat.format(wechatUser.getLastLoginTime());
            if (!nowFormat.equals(lastFormat)) {
                wechatApiService.addUserLoginGrade(wechatUser);
            }
        }
        //发放token
        String token = sysLoginService.wechatLogin(user);
        ajaxResult.put("token", token);
        return ajaxResult;
    }
}
